package com.cr.crandroid.ui.person.user;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.gridlayout.widget.GridLayout;
import androidx.navigation.Navigation;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.cr.crandroid.R;
import com.cr.crandroid.base.BaseFragment2;
import com.cr.crandroid.bean.User;
import com.cr.crandroid.utils.CommonConstant;
import com.cr.crandroid.utils.GlideEngine;
import com.cr.crandroid.utils.OConvertUtils;
import com.cr.crandroid.utils.OkHttpManager;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.UUID;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class InfoFragment extends BaseFragment2 {
    private View root;
    private EditText editText;
    private EditText editText1;
    private EditText editText2;
    private EditText editText3;
    private EditText editText4;
    private ImageView imageView;
    private ImageButton imageButton;
    private GridLayout gridLayout;
    private User user = new User();
    private String url = CommonConstant.URL + "/user/edit";
    private String image_upload_url = CommonConstant.URL + "/upload/uploadUserImage";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fragment_info, container, false);
        editText = root.findViewById(R.id.editText);
        editText1 = root.findViewById(R.id.editText1);
        editText2 = root.findViewById(R.id.editText2);
        editText3 = root.findViewById(R.id.editText3);
        editText4 = root.findViewById(R.id.editText4);
        imageView = root.findViewById(R.id.imageView);
        imageButton = root.findViewById(R.id.imageButton);
        gridLayout = root.findViewById(R.id.gridLayout);
        // 初始化当前用户信息
        initUser();
        selectImage();
        Button buttonSave = root.findViewById(R.id.buttonSave);
        buttonSave.setOnClickListener(this::save);
        Button button = root.findViewById(R.id.button);
        button.setOnClickListener(this::logout);
        return root;
    }

    // 初始化显示用户信息
    private void initUser(){
        if (!LoginViewModel.user.isJsonNull()) {
            if (LoginViewModel.user.get("avatar") != null) {
                // 设置为可见状态
                imageView.setVisibility(View.VISIBLE);
                // 使用Glide库来加载一张图片
                Glide.with(getContext()).load(OConvertUtils.getString(LoginViewModel.user.get("avatar").toString())).into(imageView);
            }else{
                imageView.setImageResource(R.drawable.default_head);
            }
            editText.setText(OConvertUtils.getString(LoginViewModel.user.get("username").toString()));
            editText1.setText(OConvertUtils.getString(LoginViewModel.user.get("email").toString()));
            editText2.setText(OConvertUtils.getString(LoginViewModel.user.get("realName").toString()));
            editText3.setText(Integer.parseInt(OConvertUtils.getString(LoginViewModel.user.get("sex").toString())) == 1 ? "男" : "女");
            editText4.setText(OConvertUtils.getString(LoginViewModel.user.get("phone").toString()));
        }
    }

    private void selectImage(){
        // 点击监听器，例如选择一张图片的操作
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 创建一个相册选择器实例
                EasyPhotos.createAlbum(getActivity(), true, false, GlideEngine.getInstance())//参数说明：上下文，是否显示相机按钮，是否使用宽高数据（false时宽高数据为0，扫描速度更快）
                        .setFileProviderAuthority("com.cr.crandroid.fileprovider")
                        .setCount(1)        // 图片最多数量为1
                        .start(new SelectCallback() {
                            @Override
                            public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                                // 删除已选择的图片，重新添加
                                gridLayout.removeAllViews();
                                gridLayout.addView(imageView);
                                gridLayout.addView(imageButton);
                                String imagePath = "";
                                // 设置图片为可见状态，并加载已选中的图片
                                imageView.setVisibility(View.VISIBLE);
                                GlideEngine.getInstance().loadPhoto(getContext(), photos.get(0).uri, imageView);

                                // 上传图片到服务器，传参为一个MultipartFile文件
                                byte[] imgBytes = photoToBytes(photos.get(0));
                                // 上传图片方法
                                uploadPhotoToServer(imgBytes);
                            }

                            @Override
                            public void onCancel() {
                            }
                        });
            }
        });
    }

    // Photo 转换为 byte数组
    private byte[] photoToBytes(Photo photo) {
        try {
            InputStream inputStream = requireContext().getContentResolver().openInputStream(photo.uri);
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            return stream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private void uploadPhotoToServer(byte[] photoBytes) {
        OkHttpClient client = new OkHttpClient();

        // 避免文件名冲突，使用随机数
        String fileName = UUID.randomUUID().toString();

        // 创建RequestBody
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", fileName+".jpg", RequestBody.create(MediaType.parse("image/jpeg"), photoBytes))
                .build();

        // 创建Request
        Request request = new Request.Builder()
                .url(image_upload_url)
                .post(requestBody)
                .build();

        // 发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 处理结果
                String responseBody = response.body().string();
                JsonParser parser = new JsonParser();
                JsonObject jsonObject = parser.parse(responseBody).getAsJsonObject();
                String success = jsonObject.getAsJsonObject().get("success").toString();
                String message = jsonObject.getAsJsonObject().get("message").toString();
                if(success.equals("true")){
                    JsonObject result = jsonObject.getAsJsonObject("result");
                    // 获取图片路径
                    String imageUrl = result.get("url").getAsString();

                    //  确保在主线程中更新 UI
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            user.setAvatar(imageUrl); // 假设这是一个方法，用于设置 ImageView 的 URL 或加载图片
                        }
                    });
                    Snackbar.make(getView(), "用户头像加载成功", Snackbar.LENGTH_LONG).show();
                }else{
                    Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).show();
                }
            }
        });
    }

    // 退出登录
    private void logout(View view) {
        Snackbar.make(view, "退出登录成功", Snackbar.LENGTH_LONG).show();
        LoginViewModel.user = new JsonObject();
        Navigation.findNavController(view).navigateUp();
    }

    // 保存用户信息
    private void save(View view){
        String username = editText.getText().toString();
        String email = editText1.getText().toString();
        String realName = editText2.getText().toString();
        String sex = editText3.getText().toString();
        String phone = editText4.getText().toString();
        if (TextUtils.isEmpty(username)) {
            editText.setError("用户名不能为空");
            return;
        }
        if (TextUtils.isEmpty(email)) {
            editText1.setError("电子邮件不能为空");
            return;
        }
        if (TextUtils.isEmpty(realName)) {
            editText1.setError("真实姓名不能为空");
            return;
        }
        if (TextUtils.isEmpty(sex)) {
            editText1.setError("性别不能为空");
            return;
        }
        if (TextUtils.isEmpty(phone)) {
            editText1.setError("手机号不能为空");
            return;
        }
        user.setId(OConvertUtils.getString(LoginViewModel.user.get("id").toString()));
        user.setUsername(username);
        user.setEmail(email);
        user.setPhone(phone);
        user.setSex(sex);
        user.setRealName(realName);
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpManager.postJ(url, new Gson().toJson(user), new Callback() {
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String res = response.body().string();
                        JsonObject result = JsonParser.parseString(res).getAsJsonObject();
                        if (result.get("success").getAsBoolean()) {
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                            LoginViewModel.user = JsonParser.parseString(String.valueOf(result.get("result"))).getAsJsonObject();
                            Snackbar.make(view, result.get("message").getAsString(), Snackbar.LENGTH_LONG).show();
                        }
                    }
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {

                    }
                });
            }
        }).start();
    }
}